package net.bwie.realtime.jtp.dws.log.function;

import net.bwie.realtime.jtp.dws.log.bean.PageViewBean;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @Author: FuHe
 * @Date: 2025/5/19
 */
public class PageViewWindomFunction implements WindowFunction<PageViewBean, String, String, TimeWindow> {
    // 格式化时间字段
    private FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    @Override
    public void apply(String s, TimeWindow window, Iterable<PageViewBean> input, Collector<String> out) throws Exception {
        // 窗口开始时间
        String windowStartTime = format.format(window.getStart());
        // 窗口结束时间
        String windowEndTime = format.format(window.getEnd());
        // 对窗口的数据计算
        Long pvCount = 0L;
        Long pvDuringTime = 0L;
        Long uvCount = 0L;
        Long sessionCount = 0L;
        for (PageViewBean bean : input) {
            pvCount += bean.getPvCount();
            pvDuringTime += bean.getPvDuringTime();
            uvCount += bean.getUvCount();
            sessionCount += bean.getSessionCount();
        }
        // 输出
        String output = windowStartTime + ","
                + windowEndTime + ","
                + s + ","
                + pvCount + ","
                + pvDuringTime + ","
                + uvCount + ","
                + sessionCount + ","
                + System.currentTimeMillis();
        out.collect(output);
    }
}
